package com.sharemarking.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sharemarking.system.dto.Page;
import com.sharemarking.system.dto.Select2Dto;
import com.sharemarking.system.dto.agreement.AgreementListDto;
import com.sharemarking.system.dto.orgVerify.OrgVerifyListDto;
import com.sharemarking.system.mapper.AgreementMapper;
import com.sharemarking.system.mapper.AreaMapper;
import com.sharemarking.system.mapper.OrgVerifyMapper;
import com.sharemarking.system.service.JGPushService;
import com.sharemarking.wa.common.entity.Agreement;
import com.sharemarking.wa.common.entity.OrgVerify;
import com.sharemarking.wa.common.entity.OrgVerifyAttachment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dxy
 */
@Controller
@RequestMapping("system/productWasteOrgVerify")
public class ProductWasteOrgVerifyController {
    @Autowired
    private OrgVerifyMapper om;
    @Autowired
    private HttpSession session;
    @Autowired
    private JGPushService jgPushService;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private AgreementMapper agreementMapper;

    /**
     * 列表页面
     * @param
     * @param model
     */
    @GetMapping("index")
    @PreAuthorize("hasPermission('base','all')")
    public String index(OrgVerifyListDto obj, Integer page, Model model, Integer isSession){
        int size=10;
        if(page==null) {
            page=0;
        }
        // session 参数回显
        if (isSession != null) {
            // 如果isSession为1，代表要从session取条件参数，一般应用在某操作之后要保存查询参数
            obj = session.getAttribute("query") == null ? obj : (OrgVerifyListDto) session.getAttribute("query");
            size = session.getAttribute("size") == null ? size : (int) session.getAttribute("size");
            page = session.getAttribute("page") == null ? page : (int) session.getAttribute("page");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("pageIndex",page*size);
        map.put("pageSize",size);

        if(!StringUtils.isEmpty(obj.getExamState())) {
            map.put("examState",obj.getExamState());
        }
        if(!StringUtils.isEmpty(obj.getMobile())) {
            map.put("mobile",obj.getMobile());
        }
        if(!StringUtils.isEmpty(obj.getOrgName())) {
            map.put("orgName",obj.getOrgName());
        }
        List<OrgVerifyListDto> list=om.getProductWasteOrgList(map);
        int total = om.getProductWasteOrgListTotal(map);
        model.addAttribute("page", new Page<>(page, size, total, list));
        model.addAttribute("query",obj);
        // session 参数保存
        session.setAttribute("query",obj);
        session.setAttribute("size", size);
        session.setAttribute("page", page);
        return "orgVerify/productWasteIndex";
    }


    /**
     * 新增、编辑页面
     * @param obj
     * @param model
     * @return
     */
    @GetMapping("{id}")
    @PreAuthorize("hasPermission('base','all')")
    public String get(@PathVariable("id")int id, Model model){
        OrgVerify obj = new OrgVerify();
        if (id > 0) {
            obj = om.selectById(id);
        }else {
            model.addAttribute("obj",obj);
        }
        List<String> attach = om.getAttachList(id);
        model.addAttribute("attach",attach);
        model.addAttribute("attachStr",String.join(",",attach));
        model.addAttribute("businessLicense",om.getAttach(id));
        model.addAttribute("obj",obj);
        model.addAttribute("areaList", areaMapper.getList("001"));
        return "orgVerify/productWasteForm";
    }

    /**
     * 新增、编辑
     * @param obj
     * @param model
     * @return
     */
    @PostMapping("{id}")
    @PreAuthorize("hasPermission('base','all')")
    @Transactional
    public String post(OrgVerify obj, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) throws Exception{
        if (obj.getProvince() != null) {
            obj.setProvince(areaMapper.get(obj.getProvince()).getName());
        }
        if (obj.getCity() != null) {
            obj.setCity(areaMapper.get(obj.getCity()).getName());
        }
        if (obj.getArea() != null) {
            obj.setArea(areaMapper.get(obj.getArea()).getName());
        }

        if (obj.getId() == 0) {
            om.insert(obj);
        }else {
            om.updateById(obj);
            OrgVerify orgVerify = om.selectById(obj.getId());
            if (orgVerify != null && orgVerify.getExamState() == 1) {
                om.updateOrgRealName(orgVerify.getOrgId(), orgVerify.getName());
            }
        }
        String attachStr= request.getParameter("attachStr");
        if (!StringUtils.isEmpty(attachStr)){
            om.deleteAttach(obj.getId());
            String [] attachList = attachStr.split(",");
            for (String s : attachList){
                if (!StringUtils.isEmpty(s)){
                    OrgVerifyAttachment orgVerifyAttachment = new OrgVerifyAttachment();
                    orgVerifyAttachment.setAttachment(s);
                    orgVerifyAttachment.setType(0);
                    orgVerifyAttachment.setOrgVerifyId(obj.getId());
                    orgVerifyAttachment.setCreateDate(new Date());
                    om.insertAttach(orgVerifyAttachment);
                }
            }
        }
        model.addAttribute("obj",obj);
        redirectAttributes.addFlashAttribute("msg","操作成功!");
        return "redirect:index?isSession=1";
    }


    /**
     * 详情页面
     * @param obj
     * @param model
     * @return
     */
    @GetMapping("info/{id}")
    @PreAuthorize("hasPermission('base','all')")
    public String getInfo(@PathVariable("id")int id, Model model){
        OrgVerify obj = new OrgVerify();
        if (id > 0) {
            obj = om.selectById(id);
        }else {
            model.addAttribute("obj",obj);
        }
        List<String> attach = om.getAttachList(id);
        List<AgreementListDto> agreementList = agreementMapper.getListByOrgId(obj.getOrgId());
        model.addAttribute("attach",attach);
        model.addAttribute("obj",obj);
        model.addAttribute("businessLicense",om.getAttach(id));
        model.addAttribute("agreementList",agreementList);
        return "orgVerify/pwInfo";
    }

    /**
     * 审核
     * @param obj
     * @param model
     * @return
     */
    @GetMapping("exam")
    @PreAuthorize("hasPermission('base','all')")
    @Transactional
    public String exam(int id, int type, String rejectReason, Model model, RedirectAttributes redirectAttributes){
        OrgVerify orgVerify = new OrgVerify();
        OrgVerify orgVerify1 = om.selectById(id);
        orgVerify.setExamState(type);
        String messageStr = null;
        if(type == 2) {
            if(StringUtils.isEmpty(rejectReason)) {
                redirectAttributes.addFlashAttribute("msg","驳回理由不可为空！");
                return "redirect:index?isSession=1";
            }
            orgVerify.setRejectReason(rejectReason);
            om.updateOrgRealNameNull(orgVerify1.getOrgId());
            messageStr = "您好，您的企业认证已被驳回，驳回理由是：" + rejectReason;
        }else {
            orgVerify.setRejectReason(null);
            //通过协议认证
            agreementMapper.updateExamState(id,1);
            //冗余org的real_name
            om.updateOrgRealName(orgVerify1.getOrgId(),orgVerify1.getName());
            messageStr = "您好，您的企业认证已通过。";
        }
        orgVerify.setId(id);
        orgVerify.setUpdateDate(new Date());
        om.updateById(orgVerify);

        jgPushService.pushTag(messageStr,orgVerify1.getMemberId());


        redirectAttributes.addFlashAttribute("msg","操作成功！");
        return "redirect:index?isSession=1";
    }

    @GetMapping("getAreaList")
    @ResponseBody
    @PreAuthorize("hasPermission('base','all')")
    public List<Select2Dto> getDepartmentList(String parentId) {
        List<Select2Dto> list = areaMapper.getList(parentId);
        return list;
    }
}
